package com.eagle.epay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eagle.epay.constant.MallConst;
import com.eagle.epay.entity.Category;
import com.eagle.epay.entity.User;
import com.eagle.epay.mapper.CategoryMapper;
import com.eagle.epay.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eagle.epay.vo.CategoryVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author eagle
 * @since 2019-12-21
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

	@Override
	public List<CategoryVo> getCategoryList() {
		QueryWrapper<Category> wrapper = new QueryWrapper<>();
		wrapper.eq("status", 1);
		List<Category> categoryList = this.list(wrapper);
		List<CategoryVo> categoryVos = categoryList.stream().filter(s -> s.getParentId() == MallConst.ROOT_PARENT_ID)
				.map(this::copy)
				.sorted(Comparator.comparing(CategoryVo::getSortOrder).reversed())
				.collect(Collectors.toList());
		this.populateSubCategory(categoryList, categoryVos);
		return categoryVos;
	}

	@Override
	public Set<Integer> getCategoryById(Integer categoryId) {
		QueryWrapper<Category> wrapper = new QueryWrapper<>();
		wrapper.eq("status", 1);
		List<Category> categoryList = this.list(wrapper);
		Set<Integer> categoryIds = new HashSet();
		this.getCategoryById(categoryList,categoryIds,categoryId);
		return categoryIds;
	}

	private void getCategoryById(List<Category> categoryList, Set<Integer> categoryIds, Integer categoryId){
		for (Category category : categoryList) {
			if(category.getParentId().equals(categoryId)){
				categoryIds.add(category.getId());
				getCategoryById(categoryList,categoryIds,category.getId());
			}
		}
	}

	private void populateSubCategory(List<Category> categorySource, List<CategoryVo> categoryVos){
		for (CategoryVo vo : categoryVos) {
			List<CategoryVo> subCatgoryList = new ArrayList<>();
			for (Category category : categorySource) {
				if(category.getParentId().intValue() == vo.getId().intValue()){
					subCatgoryList.add(this.copy(category));
					subCatgoryList.sort(Comparator.comparing(CategoryVo::getSortOrder).reversed());
					vo.setSubCategories(subCatgoryList);
					this.populateSubCategory(categorySource, subCatgoryList);
				}
			}
		}
	}

	private CategoryVo copy(Category source){
		CategoryVo target = new CategoryVo();
		BeanUtils.copyProperties(source,target);
		return target;
	}
}
